package com.yanqu.road.ipdb;

import com.yanqu.road.utils.ConfigHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Objects;

@RequestMapping("/ip")
@RestController
public class IpController {

    private  City city = null;

    @RequestMapping("location")
    public String ipLocation(String ip) {
        try {
            if (city == null) {
                init();
            }
            if (city != null) {
                CityInfo cityInfo = city.findCity(ip, "CN");
                if (cityInfo != null) {
                    String countryName = cityInfo.getCountryName();
                    if (Objects.equals("中国", countryName)) {
                        return cityInfo.getRegionName();
                    }
                    return countryName;
                }
            }
        } catch (IPFormatException | InvalidDatabaseException e) {

        }
        return "";
    }

    @RequestMapping("cityName")
    public String cityName(String ip) {
        try {
            if (city == null) {
                init();
            }
            if (city != null) {
                CityInfo cityInfo = city.findCity(ip, "CN");
                if (cityInfo != null) {
                    String cityName = cityInfo.getCityName();
                    if (Objects.equals("中国", cityName)) {
                        return cityInfo.getRegionName();
                    }
                    return cityName;
                }
            }
        } catch (IPFormatException | InvalidDatabaseException e) {

        }
        return "";
    }

    private synchronized void init() {
        if (city == null) {
            try {
                String file = ConfigHelper.getValue("ipData.file");
                city = new City(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
